/*
 *  ____                   _       _ _ 
 * |  _ \                 | |     (_) |
 * | |_) |_   _  __ _     | | __ _ _| |
 * |  _ <| | | |/ _` |_   | |/ _` | | |
 * | |_) | |_| | (_| | |__| | (_| | | |
 * |____/ \__,_|\__, |\____/ \__,_|_|_|
 *               __/ |                 
 *              |___/
 *                                
 */
package org.bugjail.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bugjail.data.Person;
import org.bugjail.servlet.exception.MissingParameterException;
import org.bugjail.servlet.exception.PermissionException;

/**
 * Servlet implementation class for Servlet: BasicServlet
 * 
 */
public abstract class BasicServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	private Person user;

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public BasicServlet() {
		super();
	}

	protected abstract void beforeAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException;

	protected abstract void action(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException;

	protected final Person getLoggedUser() {
		return user;
	}

	protected final void doAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		user = ServletUtilities.getLogedUser(request);
		if (user != null) {
			try {
				beforeAction(request, response);
				action(request, response);
			} catch (MissingParameterException e) {
				response.sendRedirect("MissingParameterServlet");
			} catch (PermissionException e) {
				response.sendRedirect("NoPermissionServlet");
			} catch (Throwable t) {
				response.sendRedirect("ErrorServlet");
			}
		} else {
			System.out.println("URL: "+request.getRequestURL().toString()+"?"+request.getQueryString());
			response.sendRedirect("login.htm");
		}
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected final void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected final void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	public String retrieveAllowedStringFromData(String data) {
		return data;
	}
}